package com.wz.dhs.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Component
public class OssUtil {

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    /**
     * 上传文件到OSS
     *
     * @param file 待上传的文件
     * @return 文件的访问URL
     */
    public String uploadFile(MultipartFile file) {
        // 创建OSS客户端
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 获取文件输入流
            InputStream inputStream = file.getInputStream();

            // 生成唯一的文件名
            String originalFilename = file.getOriginalFilename();
            String fileName = UUID.randomUUID().toString() +
                    (originalFilename != null ? originalFilename.substring(originalFilename.lastIndexOf(".")) : "");

            // 上传文件到指定的Bucket
            ossClient.putObject(bucketName, fileName, inputStream);

            // 返回文件的访问URL（公有读）
            return "https://" + bucketName + "." + endpoint + "/" + fileName;
        } catch (Exception e) {
            throw new RuntimeException("文件上传失败", e);
        } finally {
            // 关闭OSS客户端
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
